<template>
    <div class="home-container">
        <!-- 欢迎区 -->
        <div class="welcome-section">
            <div class="welcome-content">
                <h1>🌸 鲜花论坛</h1>
                <p>分享知识，交流经验，共同成长</p>
            </div>

            <div v-if="userInfo.role === 'admin'" class="admin-buttons">
                <el-button type="primary" @click="router.push('/admin/statistics')">统计管理</el-button>
                <el-button type="primary" @click="router.push('/admin/banner')" style="margin-left: 10px;">轮播图管理</el-button>
                <el-button type="primary" @click="router.push('/admin/posts')" style="margin-left: 10px;">帖子管理</el-button>
                <el-button type="primary" @click="router.push('/admin/orders')" style="margin-left: 10px;">订单管理</el-button>
                <el-button type="primary" @click="router.push('/admin/comments')" style="margin-left: 10px;">评论管理</el-button>
            </div>

        </div>


            <!-- 轮播图 -->
            <div class="banner-section" v-if="banners.length">
                <el-carousel height="320px" indicator-position="outside">
                    <el-carousel-item v-for="banner in banners" :key="banner.id">
                        <div class="banner-item" :style="{ backgroundImage: `url(${banner.imageUrl})` }">
                            <div class="banner-content">
                                <h2>{{ banner.title }}</h2>
                                <p>{{ banner.description }}</p>
                            </div>
                        </div>
                    </el-carousel-item>
                </el-carousel>
            </div>

        <!-- 统计区 -->
        <div class="stats-section">
            <div ref="chartRef" style="width: 100%; height: 400px;"></div>
        </div>

        <!-- 热门帖子区 -->
        <div class="hot-posts-section">
            <h2>🔥 热门帖子</h2>
            <div class="posts-grid">
                <div v-for="post in hotPosts" :key="post.id" class="post-card" @click="goToPost(post.id)">
                    <div class="post-header">
                        <span>{{ post.nickname }}</span>
                        <span>{{ formatDate(post.gmtCreate) }}</span>
                    </div>
                    <div class="post-content">
                        {{ post.content }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import {getBanners} from "../api/home";

const router = useRouter()
const stats = ref({ userCount: 0, postCount: 0, replyCount: 0 })
const hotPosts = ref([])
const banners = ref([])
const userInfo = ref({})
const chartRef = ref(null)
const chartInstance = ref(null)
const chartData = ref({ xlist: [], ylist: [] })


const fetchUserInfo = async () => {
    const token = localStorage.getItem('token')
    if (token) {
        const res = await axios.get('http://localhost:10010/serviceUcenter/ucenter/getUserInfoForJwt', {
            headers: { Authorization: `Bearer ${token}` }
        })
        if (res.data && res.data.success) {
            userInfo.value = res.data.data.userInfo
        }
    }
}


const fetchBanners = async () => {
    try {
        const res = await getBanners(1, 5)
        if (res.data && res.data.success) {
            banners.value = res.data.data.rows || []
            console.log('banners:', banners.value)
        }
    } catch (e) {
        // 可忽略错误
    }
}


const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN')
}

const goToPost = (id) => {
    router.push(`/help/detail/${id}`)
}

const fetchStats = async () => {
    // TODO: 等待後端統計接口接入，這裡暫時不賦值
}

const fetchHotPosts = async () => {
    try {
        // 查詢全部熱門帖子
        const res = await axios.get('http://localhost:10010/eduservice/edu-comment/getCommentPage/1/5')
        if (res.data && res.data.success) {
            hotPosts.value = res.data.data.list || []
        }
    } catch (e) {}
}

const fetchChartData = async () => {
    const chartType = localStorage.getItem('homeChartType') || 'register_num'
    const beginDate = localStorage.getItem('homeChartBegin') || '2025-07-01'
    const endDate = localStorage.getItem('homeChartEnd') || '2025-07-22'
    const res = await axios.get(`http://localhost:10010/staservice/daily/showData/${chartType}/${beginDate}/${endDate}`)
    if (res.data && res.data.success) {
        chartData.value = res.data.data
    }
}

onMounted(async () => {
    fetchUserInfo()
    fetchStats()
    fetchHotPosts()
    fetchBanners()
    await fetchChartData()
    nextTick(() => {
        if (chartRef.value) {
            chartInstance.value = echarts.init(chartRef.value)
            chartInstance.value.setOption({
                title: { text: '註冊用戶趨勢' },
                xAxis: { type: 'category', data: chartData.value.xlist },
                yAxis: { type: 'value' },
                series: [{ data: chartData.value.ylist, type: 'line' }]
            })
        }
    })
})
</script>

<style scoped>

.admin-buttons {
    position: absolute;
    right: 32px;
    bottom: 24px;
    z-index: 2;
}
.welcome-section {
    position: relative;
    /* 其它原有样式 */
}

.banner-section {
    max-width: 900px;
    margin: 32px auto 0 auto; /* 上下有间距，居中 */
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(102, 126, 234, 0.08);
    background: #fff;
}
.banner-item {
    height: 320px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    display: flex;
    align-items: flex-end;
    justify-content: flex-start;
    position: relative;
}
.banner-content {
    color: white;
    z-index: 1;
    padding: 24px 32px;
    background: rgba(0,0,0,0.3);
    border-radius: 0 0 16px 16px;
    width: 100%;
}
.banner-content h2 {
    font-size: 2rem;
    font-weight: 700;
    margin: 0 0 8px 0;
    text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}
.banner-content p {
    font-size: 1.1rem;
    margin: 0;
    opacity: 0.9;
}

.welcome-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 16px;
    padding: 32px 24px; /* 原来是48px，改小一点 */
    text-align: center;
    margin-bottom: 24px; /* 原来是40px，改小一点 */
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}
.welcome-content h1 {
    font-size: 2.2rem; /* 原来是2.5rem，改小一点 */
    margin-bottom: 12px;
}
.welcome-content p {
    font-size: 1.1rem;
    margin-bottom: 20px;
}
.home-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 40px 10px;
}

.stats-section {
    margin-bottom: 40px;
}
.stats-container {
    display: flex;
    justify-content: space-around;
    gap: 24px;
}
.stat-item {
    background: white;
    border-radius: 12px;
    padding: 24px 32px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    text-align: center;
}
.stat-number {
    font-size: 2rem;
    font-weight: bold;
    color: #667eea;
}
.stat-label {
    color: #6c757d;
    margin-top: 8px;
}
.hot-posts-section {
    margin-top: 40px;
}
.hot-posts-section h2 {
    font-size: 1.5rem;
    margin-bottom: 24px;
    color: #2c3e50;
}
.posts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
}
.post-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    padding: 20px;
    cursor: pointer;
    transition: box-shadow 0.2s;
}
.post-card:hover {
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}
.post-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    color: #667eea;
    font-weight: bold;
}
.post-content {
    color: #2c3e50;
    font-size: 1.1rem;
}
@media (max-width: 700px) {
    .posts-grid {
        grid-template-columns: 1fr;
    }
    .stats-container {
        flex-direction: column;
        gap: 16px;
    }
}
</style>